<template>
  <div :class="{ hidden: hidden }" class="pagination-container">
    <el-pagination
      :current-page.sync="innerPage"
      :page-size.sync="innerSize"
      :background="background"
      :layout="layout"
      :page-sizes="pageSizes"
      :pager-count="pagerCount"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { scrollTo } from "@/utils/scroll-to";

export default {
  name: "Pagination",
  props: {
    total: {
      required: true,
      type: Number,
    },
    page: {
      // 对外暴露page，用于v-model:page
      type: Number,
      default: 1,
    },
    size: {
      // 对外暴露size，用于v-model:size
      type: Number,
      default: 10,
    },
    pageSizes: {
      type: Array,
      default: function () {
        return [10, 20, 30, 50];
      },
    },
    pagerCount: {
      type: Number,
      default: function () {
        return document.body.clientWidth < 992 ? 5 : 7;
      },
    },
    layout: {
      type: String,
      default: "total, sizes, prev, pager, next, jumper",
    },
    background: {
      type: Boolean,
      default: true,
    },
    autoScroll: {
      type: Boolean,
      default: true,
    },
    hidden: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      innerPage: this.page,
      innerSize: this.size,
    };
  },
  watch: {
    page(val) {
      this.innerPage = val;
    },
    size(val) {
      this.innerSize = val;
    },
    innerPage(val) {
      this.$emit("update:page", val);
    },
    innerSize(val) {
      this.$emit("update:size", val);
    },
  },
  methods: {
    handleSizeChange(val) {
      // 如果改变后页码大于最大页数，重置为1
      if (this.innerPage * val > this.total) {
        this.innerPage = 1;
      }
      this.$emit("pagination", { page: this.innerPage, size: val });
      if (this.autoScroll) {
        scrollTo(0, 800);
      }
    },
    handleCurrentChange(val) {
      this.$emit("pagination", { page: val, size: this.innerSize });
      if (this.autoScroll) {
        scrollTo(0, 800);
      }
    },
  },
};
</script>

<style scoped>
.pagination-container {
  background: #fff;
  padding: 32px 16px;
}
.pagination-container.hidden {
  display: none;
}
</style>
